import datetime
import json
import sys
import traceback

import facade
from xjlibrary.our_file_dir import BaseDir

"""
json 格式如下
{
“step1”：{

“isFinish”：False
}
}
"""


# 执行框架图
class GlobalControl(object):
    def __init__(self, file, loggerdir):
        self.insert(file)
        self.imports()
        self.jsonfile = BaseDir.get_new_path(self.curPath, "run.json")
        self.logger = facade.get_filelogger(loggerdir)
        self.mysqlutils = facade.MysqlUtiles(BaseDir.get_new_path(self.curPath, "db.ini"), "db", self.logger)
        self.is_restart = False
        self.nowstep = ""
        self.key = ""
        self.readjson()

    def imports(self):
        pass

    def insert(self, file):
        """
        :param file:  __file__
        :return:
        """
        self.curPath = BaseDir.get_file_dir_absolute(file)
        print(self.curPath)
        sys.path.insert(0, self.curPath)  # 插入

    def writejson(self):
        jsonstrings = json.dumps(self.jsondicts, ensure_ascii=False)
        BaseDir.single_write_file(jsonstrings, BaseDir.get_new_path(self.curPath, "run.json"))

    def readjson(self):
        if BaseDir.is_file_exists(self.jsonfile):
            jsonstrings = BaseDir.single_read_file(self.jsonfile)
            print(jsonstrings)
            if jsonstrings:
                self.jsondicts = json.loads(jsonstrings)
            else:
                self.jsondicts = {}
        else:
            self.jsondicts = {}

    def check(self):
        if "end" in self.jsondicts.keys() and self.jsondicts["end"]["status"] is True:
            print("表示上次程序运行结束，本次是新的更新而不是上次发生意外而进行的继续更新")
            self.is_restart = True
        else:
            print("表示更新没有完成")
            self.is_restart = False

    def init(self):
        if self.is_restart:
            # 清空字典重新开始
            self.jsondicts = {}
            self.jsondicts["start"] = {}
            self.jsondicts["start"]["status"] = False

    def start_hook(self, key):
        pass

    def start(self):
        """
        该步骤获取应该运行哪个代码
        :return:
        """
        if not self.jsondicts:
            print("直接开始第一步")
            self.key = "1"
            self.nowstep = "step1_main()"
            return True
        thiskey = ""
        for key in self.jsondicts.keys():

            thiskey = key
            print("*****************")
            print(key)
            print(self.jsondicts[key]["isFinish"])
            if not self.jsondicts[key]["isFinish"]:
                self.key = key
                print(self.key)
                self.nowstep = "step" + key + "_main()"
                return True
            if self.start_hook(key):
                return True
        self.key = str(int(thiskey) + 1)
        self.nowstep = "step" + self.key + "_main()"
        return True

    def run(self, strings):
        """
        该步骤运行代码
        :return:
        """
        try:
            if strings == "":
                return True
            result = eval(strings)
        except:
            print(traceback.format_exc())
            return False
        return result

    def writetrue(self, errmessage=""):
        self.jsondicts[self.key] = {}
        self.jsondicts[self.key]["errmessage"] = errmessage
        self.jsondicts[self.key]["isFinish"] = True
        self.jsondicts[self.key]["time"] = (datetime.datetime.utcnow() + datetime.timedelta(hours=8)).strftime(
            "%Y-%m-%d %H:%M:%S")
        self.writejson()

    def writefalse(self, e):
        self.jsondicts[self.key] = {}
        self.jsondicts[self.key]["errmessage"] = str(e)
        self.jsondicts[self.key]["isFinish"] = False
        self.jsondicts[self.key]["time"] = (datetime.datetime.utcnow() + datetime.timedelta(hours=8)).strftime(
            "%Y-%m-%d %H:%M:%S")
        self.writejson()

    def one_check(self):
        """
        该步骤检查代码是否运行完成
        :return:
        """
        pass

    def end(self):
        self.jsondicts["end"] = {}
        self.jsondicts["end"]["status"] = True
        self.writejson()

    def work(self):
        """
        该函数控制整个流程
        :return:
        """
        print("开始工作")
        self.check()
        self.init()
        while True:
            result1 = self.start()
            print("开始第" + self.key + "步")
            result2 = self.run(self.nowstep)
            result3 = self.one_check()
            if result1 and result2 and result3:
                break
        self.end()
